<template>
  <div>
    <div class="vpc-network-network-search" style="margin: 6px 0 12px">
      <el-button
        class="search-wrapper-button"
        type="primary"
        @click="addAccessControl"
        >新 建</el-button
      >
      <el-button
        class="search-wrapper-button"
        type="warning"
        @click="exportCommon"
        >导出</el-button
      >
    </div>
    <div
      class="vpc-network-table content-wrapper el-card el-card__body is-always-shadow"
    >
      <TableComponent
        ref="tableRef"
        :table-list="state.tableData"
        :table-column-info="accessControlByVpc"
        :button-slot="true"
        @updateData="setPageInfo"
        @defaultPageData="setDefaultPage"
      >
        <template #option="{ data }">
          <div
            class="flex items-center justify-center space-x-3 sm:(space-x-1) fire-wall"
          >
            <template v-for="item in optionsButton" :key="item.name">
              <el-link
                :type="item.type"
                size="small"
                :underline="false"
                v-text="item.name"
                @click="item.click(data)"
              />
            </template>
            <img
              src="@/assets/datang/firewall_up.png"
              @click="moveStrategy(data, 'up')"
              alt=""
            />
            <img
              src="@/assets/datang/firewall_down.png"
              @click="moveStrategy(data, 'down')"
            />
            <el-link
              type="primary"
              size="small"
              :underline="false"
              v-text="'置顶'"
              @click="moveStrategy(data, 'top')"
            />
          </div>
        </template>
      </TableComponent>
    </div>
  </div>

  <AddOrEdit @updateData="getAccessControlByVpcData" />
</template>
<script setup>
import { onMounted, onUnmounted, ref, watch, shallowReactive } from 'vue';
import TableComponent from '@/components/table/TableComponent.vue';
import debounce from 'lodash/debounce';
import { accessControlByVpc } from '@/views/simulation/defaultConfig';
import { xtend } from '@/utils/common';
import { instanceToPlain } from 'class-transformer';
import {
  delAccessControlByVPCApi,
  editAccessControlByVPCApi,
  getAccessControlByVPCApi,
} from '@/api/topo/simulationApi/vpc';
import { ElMessage, ElMessageBox } from 'element-plus';
import { exportToExcel } from '@/utils/file';
import { emitter } from '@/utils/bus';
import AddOrEdit from './addOrEdit.vue';

// vpcID
const vpcID = ref('');

// 节点数据
const props = defineProps({
  vpcNode: null,
});

const tableRef = ref(null);
const pageInfo = ref(null);
const state = shallowReactive({
  tableData: [],
});

/**
 * 获取访问控制-VPC网络（防抖）
 */
const getAccessControlByVpcData = debounce(async () => {
  const searchInfo_ = xtend(instanceToPlain(pageInfo.value));

  return getAccessControlByVPCApi(vpcID.value, searchInfo_).then(res => {
    if (!(res instanceof Error)) {
      const {
        data: { list, total, page, pageSize },
      } = res;
      tableRef.value?.setPageInfo({ total, page, pageSize });
      state.tableData = list;
    }
  });
}, import.meta.env.VITE_INPUT_DEBOUNCE_TIME);

// 初始化页数
const setDefaultPage = arg => (pageInfo.value = arg);

const setPageInfo = arg => {
  pageInfo.value = arg;
  getAccessControlByVpcData();
};

const optionsButton = [
  {
    link: true,
    type: 'warning',
    name: '编辑',
    click: item => {
      emitter.emit('addOrEditAccessControl', {
        editObj: item,
        vpcID: vpcID.value,
      });
    },
  },
  {
    link: true,
    type: 'danger',
    name: '删除',
    click: item => {
      ElMessageBox.confirm(
        `删除访问控制 ，删除后将不可恢复！`,
        '删除访问控制',
        {
          confirmButtonText: '删 除',
          cancelButtonText: '取 消',
          type: 'warning',
          center: true,
          customClass: 'delMessageBox',
          confirmButtonClass: 'delButtonClass',
        },
      ).then(async () => {
        delAccessControlByVPCApi(vpcID.value, item.position).then(res => {
          if (!(res instanceof Error)) {
            ElMessage.success(`删除成功!`);
            getAccessControlByVpcData();
          }
        });
      });
    },
  },
];

/**
 * 新建
 */
const addAccessControl = () => {
  emitter.emit('addOrEditAccessControl', {
    vpcID: vpcID.value,
  });
};

/**
 * 移动策略
 * @param item
 * @param type
 */
const moveStrategy = (item, type) => {
  ElMessageBox.confirm(`是否确定移动策略?`, '移动', {
    confirmButtonText: '确 定',
    cancelButtonText: '取 消',
    type: 'warning',
    center: true,
  }).then(async () => {
    editAccessControlByVPCApi(vpcID.value, item.position, {
      ...item,
      move: type,
    }).then(res => {
      if (!(res instanceof Error)) {
        ElMessage.success('移动成功');
        getAccessControlByVpcData();
      }
    });
  });
};

/**
 * 导出
 */
const exportCommon = () => {
  exportToExcel('访问控制', state.tableData, tableRef.value.commonTableRef);
};

// 监听传递过来的节点数据
watch(
  () => props.vpcNode,
  val => {
    vpcID.value = props.vpcNode.ID
      ? props.vpcNode.ID
      : props.vpcNode.id
      ? props.vpcNode.id.substring(2)
      : null;

    getAccessControlByVpcData();
  },
  { immediate: true },
);

/**
 * 挂载-生命周期
 */
onMounted(() => {});

/**
 * 卸载-生命周期（主要处理清除定时器、解绑操作）
 */
onUnmounted(() => {});
</script>
<style lang="scss" scoped>
.vpc-network-network-search {
  margin-top: 12px;
  position: relative;

  button {
    margin-left: 16px;
  }

  .vpc-network-search {
    top: -10px !important;
  }
}

.vpc-network-table {
  padding-top: 12px;
  height: calc(100vh - 476px) !important;
}

.fire-wall {
  img {
    cursor: pointer;
  }
}
</style>
